﻿Imports EstoqueBLL
Public Class InventarioCAD
    Dim objbll As New InventarioBLL
    Dim objprod As PECABLL
    Dim tabitens As New DataTable
    Public Op As Char
#Region "Métodos"
#Region "Carrega na Datagirdview"
    Sub Carrega_Selecao(itens As ItensInventarioBLL)
        Try
            Dim soma As Decimal = 0
            Dim linha As DataRow
            linha = tabitens.NewRow
            linha("pec_codigo") = itens.pec_codigo
            linha("pec_codbarra") = objprod.pec_codbarra
            linha("pro_descricao") = objprod.pro_descricao
            linha("pec_qtde") = itens.pec_qtde
            linha("inv_qtdereal") = itens.inv_qtdereal
            tabitens.Rows.Add(linha)
            tabitens.AcceptChanges()
        Catch ex As Exception
            Throw New Exception("Erro ao inserir na grid")
        End Try
    End Sub
#End Region

#Region "Edita na Datagridview"
    Public Sub editanagrid(itens As ItensInventarioBLL, indice As Integer)
        tabitens.Rows(indice)("pec_codigo") = itens.pec_codigo
        tabitens.Rows(indice)("pec_codbarra") = objprod.pec_codbarra
        tabitens.Rows(indice)("pro_descricao") = objprod.pro_descricao
        tabitens.Rows(indice)("pec_qtde") = itens.pec_qtde
        tabitens.Rows(indice)("inv_qtdereal") = itens.inv_qtdereal
        tabitens.AcceptChanges()
    End Sub
#End Region

#Region "Valida Item"
    Function validaItem(codigopeca As Integer) As Boolean
        Dim ret As Boolean
        ret = False
        For Each linha As DataRow In tabitens.Rows
            If (linha("pec_codigo") = codigopeca) Then
                ret = True
            End If
        Next
        Return ret
    End Function

#End Region

#Region "Lista"
    Sub Lista()
        tabitens = New DataTable()
        Try
            tabitens.Columns.Add("pec_codigo", GetType(Integer))
            tabitens.Columns.Add("pec_codbarra", GetType(String))
            tabitens.Columns.Add("pro_descricao", GetType(String))
            tabitens.Columns.Add("pec_qtde", GetType(Integer))
            tabitens.Columns.Add("inv_qtdereal", GetType(Integer))
            DGVDados.DataSource = tabitens
        Catch
            Throw New Exception("Erro ao gerar lista")
        End Try

    End Sub
#End Region

#Region "Limpa"
    Sub limpa()
        tabitens = New DataTable
    End Sub
#End Region

#Region "limpa produto"
    Sub limpaproduto()
        TCodBarras.Text = ""
        TDescProduto.Text = ""
        TEstTotal.Text = "0"
        tqtdereal.Text = "0"
        objprod = Nothing
    End Sub
#End Region

#Region "Carregar Produto"
    Sub Carregaproduto()
        If (Not IsNothing(objprod)) Then
            TDescProduto.Text = objprod.pro_descricao
            TEstTotal.Text = objprod.pec_qtde
            TCodBarras.Text = objprod.pec_codigo
        End If
        tqtdereal.Clear()
    End Sub
#End Region

#Region "Carregar Campos"
    Sub carregarcampos()
        objbll = New InventarioBLL(Val(lcodigo.Text))
        tabitens = objbll.buscaritens()
        tabitens.AcceptChanges()
        DGVDados.DataSource = tabitens
        tdata.value = objbll.inv_data
    End Sub
#End Region

#Region "Buscar por codigo de barras"
    Public Sub buscacodbar()
        Dim dt As New DataTable
        objprod = New PECABLL
        dt = objprod.localizar(TCodBarras.Text, 1)
        If (dt.Rows.Count > 0) Then
            objprod = New PECABLL(Val(dt.Rows(0)("pec_codigo").ToString))
            Carregaproduto()
        Else
            limpaproduto()
            MessageBox.Show("Peça não cadastrada!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Dim frm As New PecaCON
            frm.tipo = "ret"
            frm.ShowDialog()
            If (Not IsNothing(frm.objprod)) Then
                objprod = frm.objprod
                Carregaproduto()
            End If

        End If
    End Sub
#End Region
#End Region

#Region "Eventos"
#Region "Load"

    Private Sub InventarioCAD_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            SendKeys.Send("{TAB}")
        End If
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
    Private Sub ComprasCAD_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        limpa()
        Lista()
        If (Op = "E") Then
            carregarcampos()
        End If
    End Sub
#End Region

#Region "Botão add produto"
    Private Sub TSBAdiconar_Click(sender As System.Object, e As System.EventArgs) Handles TSBAdiconar.Click
        Try
            If (Not IsNothing(objprod)) Then
                If (objprod.pro_codigo > 0) Then
                    If (Not validaItem(objprod.pec_codigo)) Then
                        Dim objiten As New ItensInventarioBLL
                        objiten.inv_qtdereal = Val(tqtdereal.Text)
                        objiten.pec_qtde = Val(TEstTotal.Text)
                        objiten.pec_codigo = Val(objprod.pec_codigo)
                        objiten.validarcampos()
                        Carrega_Selecao(objiten)
                        limpaproduto()

                        Dim indice As Integer
                        indice = -1
                        For Each linha As DataGridViewRow In DGVDados.SelectedRows
                            If (Not linha.Cells("pec_codigo") Is Nothing) Then
                                indice = linha.Index
                            End If
                        Next
                        If (indice <> -1) Then DGVDados.Rows(indice).Selected = False
                    Else
                        Throw New Exception("Item já adicionado")
                    End If
                End If
            Else
                Throw New Exception("Selecione uma peça.")
            End If



        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

    End Sub
#End Region

#Region "Voltar"
    Private Sub TSBVoltar_Click(sender As System.Object, e As System.EventArgs) Handles TSBVoltar.Click
        Me.Close()
    End Sub
#End Region

#Region "Remover da Datagridview"
    Private Sub BExcluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBExcluir.Click
        Try
            Dim indice As Integer
            indice = -1

            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pec_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                tabitens.Rows.RemoveAt(indice)
                tabitens.AcceptChanges()
            Else : Throw New Exception("Selecione uma peça para remover")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

#End Region

#Region "Editar na DataGridView"
    Private Sub TSBEditar_Click(sender As System.Object, e As System.EventArgs) Handles TSBAlterar.Click
        Try
            Dim indice As Integer
            indice = -1
            If (Not IsNothing(objprod)) Then
                For Each linha As DataGridViewRow In DGVDados.SelectedRows
                    If (Not linha.Cells("pec_codigo") Is Nothing) Then
                        indice = linha.Index
                    End If
                Next
                If (indice <> -1) Then
                    Dim objiten As New ItensInventarioBLL
                    objiten.inv_qtdereal = Val(tqtdereal.Text)
                    objiten.pec_qtde = Val(TEstTotal.Text)
                    objiten.pec_codigo = Val(objprod.pec_codigo)
                    editanagrid(objiten, indice)
                    limpaproduto()
                    DGVDados.Rows(indice).Selected = False
                Else : Throw New Exception("Selecione um produto para editar")
                End If
            Else
                Throw New Exception("Selecione um produto para editar")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub
#End Region

#Region "Salvar/Alterar"
    Private Sub TSBSalvar_Click(sender As System.Object, e As System.EventArgs) Handles TSBGravar.Click
        Try
            If (MessageBox.Show("Deseja finalizar o inventário?", "Finalização", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes) Then
                'se for fechar a compra
                objbll = New InventarioBLL(Val(lcodigo.Text), tdata.Value, 6)
                objbll.valida()
                Dim obj As ItensInventarioBLL
                For Each linha As DataRow In tabitens.Rows
                    obj = New ItensInventarioBLL
                    obj.inv_qtdereal = linha("inv_qtdereal")
                    obj.pec_codigo = linha("pec_codigo")
                    obj.pec_qtde = linha("pec_qtde")
                    obj.validarcampos()
                    objbll.litens.Add(obj)
                Next
            Else
                objbll = New InventarioBLL(Val(lcodigo.Text), tdata.Value, 4)
                Dim obj As ItensInventarioBLL
                For Each linha As DataRow In tabitens.Rows
                    obj = New ItensInventarioBLL
                    obj.inv_qtdereal = linha("inv_qtdereal")
                    obj.pec_codigo = linha("pec_codigo")
                    obj.pec_qtde = linha("pec_qtde")
                    objbll.litens.Add(obj)
                Next
            End If
            If (objbll.litens.Count <= 0) Then Throw New Exception("Insira ao menos um item no inventário")
            objbll.inseriralterar(objusuarios.Codigo)
            If (objbll.sta_codigo = 6) Then
                objbll.atualiza()
            End If
            MessageBox.Show("Inventário gravado com sucesso", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information)
            limpa()
            Me.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub
#End Region

#Region "Keypress"
    Private Sub TCodBarras_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TCodBarras.KeyPress
        If Not (Char.IsNumber(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True
        If (e.KeyChar = Convert.ToChar(Keys.Return)) Then
            buscacodbar()
        End If
    End Sub
    Private Sub TEstTotal_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TEstTotal.KeyPress, tqtdereal.KeyPress
        If Not (Char.IsNumber(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True
    End Sub
#End Region

#Region "Botão Busca Produto"
    Private Sub BBuscaProduto_Click(sender As System.Object, e As System.EventArgs) Handles BBuscaProduto.Click
        Dim frm As New PecaCON
        frm.tipo = "ret"
        frm.ShowDialog()
        If (Not IsNothing(frm.objprod)) Then
            objprod = frm.objprod
            Carregaproduto()
        End If
    End Sub
#End Region

#Region "Click da Grid"
    Private Sub DGVDados_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVDados.CellClick
        objBLL = Nothing
        If (e.RowIndex >= 0) Then
            objprod = New PECABLL(Val(DGVDados.Rows(e.RowIndex).Cells(1).Value))
            TCodBarras.Text = objprod.pec_codigo
            TDescProduto.Text = objprod.pro_descricao
            TEstTotal.Text = (Val(DGVDados.Rows(e.RowIndex).Cells(4).Value))
            tqtdereal.Text = (Val(DGVDados.Rows(e.RowIndex).Cells(5).Value))
        End If
    End Sub
#End Region
#End Region
End Class